### llama classifier, requires ollama installed
library(tibble)
library(rollama)
library(data.table)
pull_model("llama3.1")

create_query <- function(systemmsg, texttoclassify, classification_question) {
  # Start with the system message
  q <- tribble(
    ~role,    ~content,
    "system", systemmsg
  )
  
  # Add the current text to classify along with the classification question
  usermsg_final <- paste("text:", texttoclassify, "\n", classification_question)
  q <- add_row(q, role = "user", content = usermsg_final)
  
  return(q)
}

create_summary <- function(systemmsg, texttosummarize){
  tribble(
    ~role,    ~content,
    "system", systemmsg1,
    "user",    texttosummarize)
}

systemmsg1 <- "Explain the text in terms of its objective"
systemmsg2 <- "You are assigned the task of identifying which broad groups of society, Labour and Consumers and Environmenalists or Business and Industry and Financial interests stand to gain the most from the introduction of the policy. Think carefully! Answer with only the correct category"



llm_pos_text <- function(x, systemmsg1, systemmsg2){
  q_sum <- create_summary(systemmsg1, x)
  tt <- query(q_sum, model = "llama3.1", model_params = list(seed = 4364, temprature = 1), screen = FALSE)
  q_zs <- create_query(systemmsg2, unclass(tt$message$content), "Categories: Labour and Consumers and Environmenalist, Business and Industry and Financial interests, Neither")
  category <-   query(q_zs, model = "llama3.1", model_params = list(seed = 4364, temprature = 1), screen = FALSE)
  return(category$message$content)
} 


legis <- legis[, llm_class := sapply(fulltext, function(x) suppressMessages(llm_pos_text(x,systemmsg1, systemmsg2))),]
##### code llm_class as scores
legis$llm_class <- case_when(legis$llm_class == "Labour and Consumers and Environmentalist."  ~ "left",
                             legis$llm_class == "Labour and Consumers and Environmentalist" ~ "left",
                             legis$llm_class == "Labour and Consumers and Environmentalists" ~ "left",
                             legis$llm_class == "Categories: Labour and Consumers and Environmentalists" ~ "left",
                             legis$llm_class == "Business and Industry and Financial interests"  ~ "right",
                             legis$llm_class == "Business and Industry and Financial interests." ~ "right",
                             legis$llm_class == "Categories: Business and Industry and Financial interests"  ~ "right", 
                             TRUE ~ "neither")


legis <- legis[, llm_score := sapply(llm_class,function(x) position(x)),]